package cn.tansanqinger.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class DOMDemo {
    public static void main(String[] args) {
        try {
            //得到DOM解析器的工厂实例
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            //从DOM工厂中获得DOM解析器
            DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
            //把要解析的xml文档读入DOM解析器
            Document doc = dbBuilder.parse("general/resources/person.xml");
            System.out.println("处理该文档的DomImplementation对象  = " + doc.getImplementation());
            //得到文档名称为Student的元素的节点列表
            NodeList nList = doc.getElementsByTagName("person");
            //遍历该集合，显示结合中的元素及其子元素的名字
            for (int i = 0; i < nList.getLength(); i++) {
                Element node = (Element) nList.item(i);
                System.out.println("name: " + node.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
                System.out.println("age: " + node.getElementsByTagName("age").item(0).getFirstChild().getNodeValue());
                if(node.getElementsByTagName("sex").item(0)!=null){
                    System.out.println("sex: " + node.getElementsByTagName("sex").item(0).getFirstChild().getNodeValue());
                }
                NodeList birthdayNode = node.getElementsByTagName("birthday");
                for (int j = 0; j < birthdayNode.getLength(); j++) {
                    Element birthdayElement = (Element) birthdayNode.item(i);
                    System.out.print("birthday: year: " + birthdayElement.getElementsByTagName("year").item(0).getFirstChild().getNodeValue());
                    System.out.print(" month: " + birthdayElement.getElementsByTagName("month").item(0).getFirstChild().getNodeValue());
                    System.out.print(" day: " + birthdayElement.getElementsByTagName("day").item(0).getFirstChild().getNodeValue()+"\n");
                }
            }
        } catch(Exception e) {
            e.printStackTrace();
        }

//        try {
//            File f = new File("general/resources/person.xml");
//            //获取DocumentBuilderFactory
//            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//            //通过DocumentBuilder工厂产生一个DocumentBuilder
//            DocumentBuilder builder = factory.newDocumentBuilder();
//            //利用DocumentBuilder产生Document
//            Document doc = builder.parse(f);
//            NodeList nl = doc.getElementsByTagName("person");
//            for (int i = 0; i < nl.getLength(); i++) {
//                System.out.println("name:"+ doc.getElementsByTagName("name").item(i).getFirstChild().getNodeValue());
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }
}
